﻿using AutoMapper;
using IMES.Common.Domain.DurianModel;
using IMES.Common.Domain.KeepModel.Process;
using IMES.Common.Domain.KeepModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;
using IMES.Common.Domain.SirModel;
using Keep.API.Common.L.Dtos;

namespace Keep.API.Appliction.Command.workSheetFile
{
	/// <summary>
	/// 自动更新工单
	/// </summary>
	public class workSheetAcceptCreateHandler : IRequestHandler<workSheetAcceptCreateCommon, Result>
	{
		private readonly IBaseRepositorys<workSheet> _workSheetReq;//工单
		private readonly IBaseRepositorys<TaskTable> _taskTableReq;//任务表
		private readonly IBaseRepositorys<Product> _productReq;//产品表
		private readonly IBaseRepositorys<ProcessRoute> _processRouteRep; //工艺路线表
		private readonly IBaseRepositorys<WorkingProcedure> _workingProcedureReq; //工艺工序表
		private readonly IBaseRepositorys<ProcessManagement> _processManagementRep;//工序表
		private readonly IMapper _mapper;
		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="workSheetReq"></param>
		/// <param name="taskTableReq"></param>
		/// <param name="mapper"></param>
		public workSheetAcceptCreateHandler(IBaseRepositorys<workSheet> workSheetReq, IBaseRepositorys<TaskTable> taskTableReq, IBaseRepositorys<Product> productReq, IBaseRepositorys<ProcessRoute> processRouteRep, IBaseRepositorys<WorkingProcedure> workingProcedureReq, IBaseRepositorys<ProcessManagement> processManagementRep, IMapper mapper)
		{
			_workSheetReq = workSheetReq;
			_taskTableReq = taskTableReq;
			_productReq = productReq;
			_processRouteRep = processRouteRep;
			_workingProcedureReq = workingProcedureReq;
			_processManagementRep = processManagementRep;
			_mapper = mapper;
		}

		/// <summary>
		/// 新增工单
		/// </summary>
		/// <param name="request"></param>
		/// <param name="cancellationToken"></param>
		/// <returns></returns>
		public async Task<Result> Handle(workSheetAcceptCreateCommon request, CancellationToken cancellationToken)
		{

			var result = new Result() { Code = (int)CodeEnum.success, Messege = "新增工单成功" };
			var workSheetNumbersresult = "";
			try
			{
				// 保存工单信息

				var workSheets =  new workSheet ()
				{ 
					WorkSheetNumber="",
					ProductNumber="",
					Numberofpackages=0,
					ScheduledStartTime= DateTime.Today,
					ScheduledEndTime= DateTime.Today.AddHours(12).AddMinutes(59).AddSeconds(59),
					StartTime= null,
					EndTime= null,
					State= WorkSheetState.未开始,
					Remark="",
					TaskIds="",
					ProductRelatedDocuments="",
					CreateId=1,
					CreateName="小罗",
					CreateDate=DateTime.Now,
					UpdateId=null,
					UpdateName= null,
					UpdateDate= null,
					DeleteId= null,
					DeleteName= null,
					DeleteDate=false  
				};
				 
				var addwork = 0;

				foreach (var item in request.WorkDataDtos)//循环遍历接受到的参数数据
				{
					workSheets.WorkSheetNumber = item.WorkSheetNumber;//工单编号
					workSheets.ProductNumber = item.ProductNumber;//产品编号
					workSheets.Remark = item.Remark;
                    workSheets.Numberofpackages = item.Numberofpackages;
					workSheets.ProductRelatedDocuments = item.ProductRelatedDocuments;//关联单据
					addwork = _workSheetReq.Add(workSheets);
				} 
				string workSheetNumbers = workSheets.WorkSheetNumber;

				if (addwork == 0)
				{
					throw new Exception("新增工单失败");
				}
				if (workSheetNumbers.Length >= 2)
				{
					// 现在可以安全地调用Substring，因为我们知道字符串至少有2个字符长
					workSheetNumbersresult = workSheetNumbers.Substring(0, 2);
				}
				var list = new List<taskDto>();
				DateTime today = DateTime.Now;
				foreach (var item in request.WorkDataDtos)//循环遍历接受到的参数数据
				{
					//产品-工艺-工序
					var product = _productReq.GetAll().Where(a => a.ProductNumber == item.ProductNumber).ToList();
					var processRoute = _processRouteRep.GetAll().ToList();
					var workingProcedure = _workingProcedureReq.GetAll().ToList();
					var processManagement = _processManagementRep.GetAll().ToList();
					list.AddRange(from a in product
								  join b in processRoute
								  on a.ProcessRouteId equals b.ProcessRouteId
								  join c in workingProcedure
								  on b.ProcessRouteId equals c.ProcessRouteId
								  join d in processManagement
								  on c.WTypeId equals d.ProcessID
								  select new taskDto()
								  {
									  WorkSheetNumber = item.WorkSheetNumber,
									  ProcessNumber = d.ProcessNumber,
									  ProcessName = d.ProcessName,
									  ReportingAuthority = d.ReportingAuthority,
									  Matching = d.Matching,
									  AdverseList = d.AdverseList,
									  ScheduledStartTime = today.Date,
									  ScheduledEndTime = today.Date.AddTicks(-1),
									  Numberofpackages = workSheets.Numberofpackages,

								  });
				}
				foreach (var item in list)//循环遍历添加任务表数据
				{
					TaskTable taskTable = new TaskTable()
					{
						ProcessNumber = item.ProcessNumber,
						WorkSheetNumber = item.WorkSheetNumber,
						ProcessName = item.ProcessName,
						ReportingAuthority = item.ReportingAuthority,
						Matching = item.Matching,
						AdverseList = item.AdverseList,
						ScheduledStartTime = item.ScheduledStartTime,
						ScheduledEndTime = item.ScheduledEndTime,
						Numberofpackages = item.Numberofpackages,
						RealQuantity = 0,
						GoodScore = 0,
						DefectiveQuantity = 0,
						ActualTime = 0,
						ActualStartTime = null,
						ActualEndTime = null,
						State = TaskState.未开始
					};

					_taskTableReq.Add(taskTable);
				} 
			}
			catch (Exception ex)
			{
				result.Code = (int)CodeEnum.error;
				result.Messege = ex.ToString();
				throw;
			}
			return result;

		}
		 





	}
}
